package com.feicheng.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.mt.MtClientConfigration;
import com.feicheng.common.mt.Mtmd;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.persistence.entity.Amd;
import com.feicheng.persistence.service.IAmdService;
import com.feicheng.service.a.FMtService;
import com.meituan.sdk.DefaultMeituanClient;
import com.meituan.sdk.MeituanClient;
import com.meituan.sdk.auth.MeituanTokenData;
import com.meituan.sdk.auth.MeituanTokenResponse;
import com.meituan.sdk.internal.exceptions.MtSdkException;
import com.meituan.util.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController("/wx/mt")
@RequestMapping("/wx/mt")
public class MtController {

    @Autowired
    FMtService mtService;

    @Autowired
    IAmdService iAmdService;

    @Autowired
    MtClientConfigration configration;

    @PostMapping("/getmdautourl")
    public ResultInfo getAutoUrl(@RequestBody JSONObject body) {

        String mdid = body.getString("mdid");
        Long timestamp = System.currentTimeMillis() / 1000;
        Map<String,String> param = new HashMap();
        param.put("developerId", configration.getDeveloperId().toString());
        param.put("businessId", "58");
        param.put("charset", "UTF-8");
        param.put("state", mdid);
        param.put("timestamp", timestamp.toString());
        String sign = SignUtil.getSign(configration.getSignKey(), param);

        StringBuilder sburl = new StringBuilder("https://open-erp.meituan.com/general/auth?charset=UTF-8");
        sburl.append("&developerId=").append(configration.getDeveloperId().toString());
        sburl.append("&businessId=").append("58");
        sburl.append("&sign=").append(sign);
        sburl.append("&state=").append(mdid);
        sburl.append("&timestamp=").append(timestamp);
        body.put("url", sburl.toString());
        return ResultInfo.success(body);
    }

    @GetMapping(value = "/ac/callback", produces = MediaType.TEXT_HTML_VALUE)
    public String accallback(String code, String sign, Long developerId, Integer businessId, String state) {

        if (null != mtService.newMtmd(code, state)) {
            return "<html><body><h1>成功</h1></body></html>";
        } else {
            return "<html><body><h1>失败</h1></body></html>";
        }

    }


}
